//package com.aps.algorithm.heuristic;
//
//import com.aps.algorithm.core.AbstractAPSAlgorithm;
//import com.aps.common.model.APSProductModel;
//import com.aps.common.model.SchedulingResult;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
///**
// * 资源负荷均衡算法
// * 目标：最大化资源利用率，平衡各资源的工作负荷
// */
//@Slf4j
//@Component
//public class ResourceLoadBalancingAlgorithm extends AbstractAPSAlgorithm {
//
//    private static final String ALGORITHM_NAME = "ResourceLoadBalancing";
//    private static final String ALGORITHM_DESCRIPTION = "资源负荷均衡算法 - 最大化资源利用率";
//
//    @Override
//    public String getAlgorithmName() {
//        return ALGORITHM_NAME;
//    }
//
//    @Override
//    public String getAlgorithmDescription() {
//        return ALGORITHM_DESCRIPTION;
//    }
//
//    @Override
//    protected SchedulingResult doExecute(APSProductModel model) {
//        log.info("开始执行资源负荷均衡算法");
//
//        // 1. 初始化资源负荷状态
//        Map<String, Double> resourceLoads = initializeResourceLoads(model);
//
//        // 2. 按优先级排序订单
//        List<APSProductModel.ProductionOrder> sortedOrders = sortOrdersByPriority(model);
//
//        // 3. 为每个订单分配最优资源
//        List<SchedulingResult.OrderSchedule> orderSchedules = allocateOrdersToResources(sortedOrders, model, resourceLoads);
//
//        // 4. 生成排程结果
//        SchedulingResult result = createSchedulingResult(orderSchedules, model, resourceLoads);
//
//        log.info("资源负荷均衡算法执行完成，共处理 {} 个订单", sortedOrders.size());
//
//        return result;
//    }
//
//    /**
//     * 初始化资源负荷状态
//     */
//    private Map<String, Double> initializeResourceLoads(APSProductModel model) {
//        Map<String, Double> resourceLoads = new HashMap<>();
//
//        if (model.getResources().getEquipment() != null) {
//            for (APSProductModel.EquipmentResource equipment : model.getResources().getEquipment()) {
//                resourceLoads.put(equipment.getId(), 0.0);
//            }
//        }
//
//        return resourceLoads;
//    }
//
//    /**
//     * 按优先级排序订单
//     */
//    private List<APSProductModel.ProductionOrder> sortOrdersByPriority(APSProductModel model) {
//        return model.getOrders().stream()
//            .sorted(Comparator.comparing((APSProductModel.ProductionOrder order) -> calculatePriorityScore(order)).reversed())
//            .collect(Collectors.toList());
//    }
//
//    /**
//     * 计算订单优先级分数
//     */
//    private double calculatePriorityScore(APSProductModel.ProductionOrder order) {
//        double score = 0.0;
//
//        switch (order.getPriority()) {
//            case "高": score += 100; break;
//            case "中": score += 50; break;
//            case "低": score += 10; break;
//        }
//
//        score += order.getOrderAmount() / 1000.0;
//        score += order.getQuantity() / 10.0;
//
//        return score;
//    }
//
//    /**
//     * 为订单分配最优资源
//     */
//    private List<SchedulingResult.OrderSchedule> allocateOrdersToResources(
//            List<APSProductModel.ProductionOrder> orders,
//            APSProductModel model,
//            Map<String, Double> resourceLoads) {
//
//        List<SchedulingResult.OrderSchedule> orderSchedules = new ArrayList<>();
//
//        for (APSProductModel.ProductionOrder order : orders) {
//            SchedulingResult.OrderSchedule orderSchedule = createOrderSchedule(order, model);
//
//            List<SchedulingResult.OperationSchedule> operationSchedules = new ArrayList<>();
//            for (APSProductModel.Operation operation : model.getOperations()) {
//                SchedulingResult.OperationSchedule operationSchedule = createOperationSchedule(operation, order);
//
//                // 选择负荷最轻的资源
//                String bestResourceId = selectBestResource(operation, resourceLoads);
//                operationSchedule.setAssignedEquipmentId(bestResourceId);
//
//                // 更新资源负荷
//                updateResourceLoad(bestResourceId, operation, order, resourceLoads);
//
//                operationSchedules.add(operationSchedule);
//            }
//
//            orderSchedule.setOperationSchedules(operationSchedules);
//            orderSchedules.add(orderSchedule);
//        }
//
//        return orderSchedules;
//    }
//
//    /**
//     * 选择最优资源
//     */
//    private String selectBestResource(APSProductModel.Operation operation, Map<String, Double> resourceLoads) {
//        return resourceLoads.entrySet().stream()
//            .min(Comparator.comparing(Map.Entry::getValue))
//            .map(Map.Entry::getKey)
//            .orElse(resourceLoads.keySet().iterator().next());
//    }
//
//    /**
//     * 更新资源负荷
//     */
//    private void updateResourceLoad(String resourceId,
//                                   APSProductModel.Operation operation,
//                                   APSProductModel.ProductionOrder order,
//                                   Map<String, Double> resourceLoads) {
//
//        Double currentLoad = resourceLoads.get(resourceId);
//        if (currentLoad != null) {
//            double operationTime = operation.getStandardTime() * order.getQuantity() + operation.getSetupTime();
//            resourceLoads.put(resourceId, currentLoad + operationTime);
//
//            context.addMetric("resource_load_" + resourceId, currentLoad + operationTime);
//        }
//    }
//
//    /**
//     * 创建排程结果
//     */
//    private SchedulingResult createSchedulingResult(List<SchedulingResult.OrderSchedule> orderSchedules,
//                                                   APSProductModel model,
//                                                   Map<String, Double> resourceLoads) {
//
//        SchedulingResult result = new SchedulingResult();
//        result.setSchedulingId("RLB_" + System.currentTimeMillis());
//        result.setSchedulingTime(java.time.LocalDateTime.now());
//        result.setStatus("成功");
//
//        result.setOrderSchedules(orderSchedules);
//        result.setResourceUtilizations(createResourceUtilizations(resourceLoads));
//        result.setMetrics(createSchedulingMetrics(orderSchedules, resourceLoads));
//
//        return result;
//    }
//
//    /**
//     * 创建资源利用率信息
//     */
//    private Map<String, SchedulingResult.ResourceUtilization> createResourceUtilizations(Map<String, Double> resourceLoads) {
//        Map<String, SchedulingResult.ResourceUtilization> utilizations = new HashMap<>();
//
//        for (Map.Entry<String, Double> entry : resourceLoads.entrySet()) {
//            SchedulingResult.ResourceUtilization utilization = new SchedulingResult.ResourceUtilization();
//            utilization.setResourceId(entry.getKey());
//            utilization.setResourceName("Resource-" + entry.getKey());
//            utilization.setResourceType("Equipment");
//            utilization.setTotalAvailableTime(480.0); // 假设8小时工作制
//            utilization.setUsedTime(entry.getValue());
//            utilization.setIdleTime(480.0 - entry.getValue());
//            utilization.setUtilizationRate(entry.getValue() / 480.0);
//
//            utilizations.put(entry.getKey(), utilization);
//        }
//
//        return utilizations;
//    }
//
//    /**
//     * 创建排程指标
//     */
//    private SchedulingResult.SchedulingMetrics createSchedulingMetrics(
//            List<SchedulingResult.OrderSchedule> orderSchedules,
//            Map<String, Double> resourceLoads) {
//
//        SchedulingResult.SchedulingMetrics metrics = new SchedulingResult.SchedulingMetrics();
//        metrics.setTotalOrders(orderSchedules.size());
//
//        // 计算平均资源利用率
//        double totalUtilization = resourceLoads.values().stream()
//            .mapToDouble(load -> load / 480.0)
//            .sum();
//        double averageUtilization = totalUtilization / resourceLoads.size();
//        metrics.setAverageResourceUtilization(averageUtilization);
//
//        // 计算资源平衡分数
//        double variance = resourceLoads.values().stream()
//            .mapToDouble(load -> Math.pow(load / 480.0 - averageUtilization, 2))
//            .average()
//            .orElse(0.0);
//        metrics.setResourceBalanceScore(1.0 / (1.0 + variance));
//
//        // 计算总完工时间
//        double totalMakespan = resourceLoads.values().stream()
//            .mapToDouble(Double::doubleValue)
//            .max()
//            .orElse(0.0);
//        metrics.setTotalMakespan(totalMakespan);
//
//        // 计算实际总成本
//        double totalCost = orderSchedules.stream()
//            .mapToDouble(SchedulingResult.OrderSchedule::getOrderAmount)
//            .sum();
//        metrics.setTotalCost(totalCost);
//
//        return metrics;
//    }
//
//    private SchedulingResult.OrderSchedule createOrderSchedule(APSProductModel.ProductionOrder order,
//                                                              APSProductModel model) {
//        SchedulingResult.OrderSchedule orderSchedule = new SchedulingResult.OrderSchedule();
//        orderSchedule.setOrderId(order.getId());
//        orderSchedule.setCustomerName(order.getCustomerName());
//        orderSchedule.setProductModel(order.getProductModel());
//        orderSchedule.setQuantity(order.getQuantity());
//        orderSchedule.setDeliveryDate(order.getDeliveryDate());
//        orderSchedule.setPriority(order.getPriority());
//        orderSchedule.setOrderAmount(order.getOrderAmount());
//        return orderSchedule;
//    }
//
//    private SchedulingResult.OperationSchedule createOperationSchedule(APSProductModel.Operation operation,
//                                                                       APSProductModel.ProductionOrder order) {
//        SchedulingResult.OperationSchedule operationSchedule = new SchedulingResult.OperationSchedule();
//        operationSchedule.setOperationId(operation.getId());
//        operationSchedule.setOperationName(operation.getName());
//        operationSchedule.setSequence(operation.getSequence());
//        operationSchedule.setEquipmentType(operation.getEquipmentType());
//        operationSchedule.setStandardTime(operation.getStandardTime());
//        operationSchedule.setSetupTime(operation.getSetupTime());
//        operationSchedule.setPersonnelRequirement(operation.getPersonnelRequirement());
//        operationSchedule.setQualityRequirement(operation.getQualityRequirement());
//        return operationSchedule;
//    }
//}
